package com.qianfeng.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qianfeng.biz.IAddressBiz;
import com.qianfeng.biz.impl.AddressBizImpl;
import com.qianfeng.entity.Address;
import com.qianfeng.entity.User;
public class AddressServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	IAddressBiz ib=new AddressBizImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		String action = request.getParameter("action");
		if("addAddress".equals(action)){
			User ui=(User) request.getSession().getAttribute("LOGIN_USER");
			String shouhuoren = request.getParameter("shouhuoren");
			String phone = request.getParameter("phone");
			String address = request.getParameter("address");
			//将对象封装到bean中
			Address ad = new Address();
			ad.setShouhuoren(shouhuoren);
			ad.setPhone(phone);
			ad.setAddress(address);
			ad.setUserid(ui.getId());
			//使用此默认
			ad.setIsdefault("是");
			boolean success=ib.addAdd(ad);

			if(success){
				List<Address> addressList = ib.getAddressListByUserId(ui.getId());
				for (Address address2 : addressList) {
					if(address2.getIsdefault().equals("是")){
						if(!address2.getShouhuoren().equals(shouhuoren)){
							address2.setIsdefault("否");
							ib.update(address2);
							addressList = ib.getAddressListByUserId(ui.getId());
						}
					}
				}
				
				response.setContentType("text/html;charset=utf-8");
				request.getSession().setAttribute("addressList", addressList);
				out.write("<script>alert('添加成功');location.href='pay.jsp'</script>");
				
			
			}else{
				out.write("<script language='javascript'>alert('添加失败');</script>");
				response.sendRedirect("Address.jsp");
			}
			
		}
	}

}
